/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExecutarControlador.java
 *
 * Created on 19/12/2010, 15:24:32
 */

package br.ufrn.engcomp.pds.helloopc.visao;

import br.ufrn.engcomp.pds.helloopc.controle.ExecutarControladorController;
import br.ufrn.engcomp.pds.helloopc.modelo.dominio.Controlador;
import br.ufrn.engcomp.pds.helloopc.modelo.dominio.TipoVariavelOPC;
import br.ufrn.engcomp.pds.helloopc.modelo.dominio.VariavelControlador;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;

/**
 *
 * @author Felipe Rivas
 */
public class ExecutarControlador extends JanelaBase {

    private ExecutarControladorController controller = new ExecutarControladorController();

    /** Creates new form ExecutarControlador */
    public ExecutarControlador() {
        initComponents();

        listarControladores();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bgManuseio = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cmbControladores = new javax.swing.JComboBox();
        btnExecutar = new javax.swing.JButton();
        btnParar = new javax.swing.JButton();
        pnlManuseio = new javax.swing.JPanel();
        rbAutomatico = new javax.swing.JRadioButton();
        rbManual = new javax.swing.JRadioButton();
        sprAjusteMacro = new javax.swing.JSpinner();
        lblEntrada = new javax.swing.JLabel();
        lblSaida = new javax.swing.JLabel();
        lblEntrada1 = new javax.swing.JLabel();
        lblEntrada2 = new javax.swing.JLabel();

        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(helloopc.HelloOPCApp.class).getContext().getResourceMap(ExecutarControlador.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        cmbControladores.setName("cmbControladores"); // NOI18N

        btnExecutar.setText(resourceMap.getString("btnExecutar.text")); // NOI18N
        btnExecutar.setName("btnExecutar"); // NOI18N
        btnExecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExecutarActionPerformed(evt);
            }
        });

        btnParar.setText(resourceMap.getString("btnParar.text")); // NOI18N
        btnParar.setName("btnParar"); // NOI18N
        btnParar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPararActionPerformed(evt);
            }
        });

        pnlManuseio.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("pnlManuseio.border.title"))); // NOI18N
        pnlManuseio.setName("pnlManuseio"); // NOI18N

        bgManuseio.add(rbAutomatico);
        rbAutomatico.setSelected(true);
        rbAutomatico.setText(resourceMap.getString("rbAutomatico.text")); // NOI18N
        rbAutomatico.setName("rbAutomatico"); // NOI18N
        rbAutomatico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbAutomaticoActionPerformed(evt);
            }
        });

        bgManuseio.add(rbManual);
        rbManual.setText(resourceMap.getString("rbManual.text")); // NOI18N
        rbManual.setName("rbManual"); // NOI18N
        rbManual.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbManualActionPerformed(evt);
            }
        });

        sprAjusteMacro.setModel(new javax.swing.SpinnerNumberModel(0, 0, 4000, 1));
        sprAjusteMacro.setName("sprAjusteMacro"); // NOI18N
        sprAjusteMacro.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                sprAjusteMacroStateChanged(evt);
            }
        });

        javax.swing.GroupLayout pnlManuseioLayout = new javax.swing.GroupLayout(pnlManuseio);
        pnlManuseio.setLayout(pnlManuseioLayout);
        pnlManuseioLayout.setHorizontalGroup(
            pnlManuseioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlManuseioLayout.createSequentialGroup()
                .addGroup(pnlManuseioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rbAutomatico)
                    .addGroup(pnlManuseioLayout.createSequentialGroup()
                        .addComponent(rbManual)
                        .addGap(18, 18, 18)
                        .addComponent(sprAjusteMacro, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(213, Short.MAX_VALUE))
        );
        pnlManuseioLayout.setVerticalGroup(
            pnlManuseioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlManuseioLayout.createSequentialGroup()
                .addComponent(rbAutomatico)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlManuseioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbManual)
                    .addComponent(sprAjusteMacro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        lblEntrada.setFont(resourceMap.getFont("lblEntrada.font")); // NOI18N
        lblEntrada.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblEntrada.setText(resourceMap.getString("lblEntrada.text")); // NOI18N
        lblEntrada.setName("lblEntrada"); // NOI18N

        lblSaida.setFont(resourceMap.getFont("lblEntrada.font")); // NOI18N
        lblSaida.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblSaida.setText(resourceMap.getString("lblSaida.text")); // NOI18N
        lblSaida.setName("lblSaida"); // NOI18N

        lblEntrada1.setFont(resourceMap.getFont("lblEntrada1.font")); // NOI18N
        lblEntrada1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblEntrada1.setText(resourceMap.getString("lblEntrada1.text")); // NOI18N
        lblEntrada1.setName("lblEntrada1"); // NOI18N

        lblEntrada2.setFont(resourceMap.getFont("lblEntrada1.font")); // NOI18N
        lblEntrada2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblEntrada2.setText(resourceMap.getString("lblEntrada2.text")); // NOI18N
        lblEntrada2.setName("lblEntrada2"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblEntrada2, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
                            .addComponent(lblEntrada1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblEntrada, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
                            .addComponent(lblSaida, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)))
                    .addComponent(pnlManuseio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbControladores, 0, 211, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExecutar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnParar)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblEntrada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblEntrada1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblEntrada2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblSaida))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbControladores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExecutar)
                    .addComponent(btnParar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlManuseio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(82, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnExecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExecutarActionPerformed
        // TODO add your handling code here:
        if (cmbControladores.getSelectedIndex() > 0) {
            final Controlador controladorEmExecucao = (Controlador) cmbControladores.getSelectedItem();
            
            controller.executar(controladorEmExecucao);

            Thread threadMonitoramento = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        NumberFormat nf = new DecimalFormat("+0.00;-0.00");

                        while (controller.emExecucao()) {
                            Map<String, Object> valoresEntrada = controller.getValoresEntrada();
                            Map<String, Object> valoresSaida = controller.getValoresSaida();

                            if (valoresEntrada != null) {
                                lblEntrada.setText(nf.format(valoresEntrada.get("sensor")) + " " + controladorEmExecucao.getVariavelPorNome("sensor").getUnidadeEngenharia());
                            }
                            if (valoresSaida != null) {
                                lblSaida.setText(nf.format(valoresSaida.get("controle")) + " " + controladorEmExecucao.getVariavelPorNome("controle").getUnidadeEngenharia());
                            }

                            Thread.sleep(500);
                        }
                    } catch (InterruptedException iex) {
                        iex.printStackTrace();
                        //TODO: Tratar erro
                    }
                }
            });

            threadMonitoramento.start();
        } else {
            mostrarErro("Selecione um controlador para ser executado.");
        }
    }//GEN-LAST:event_btnExecutarActionPerformed

    private void btnPararActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPararActionPerformed
        // TODO add your handling code here:
        controller.parar();
    }//GEN-LAST:event_btnPararActionPerformed

    private void rbAutomaticoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbAutomaticoActionPerformed
        // TODO add your handling code here:
        controller.colocarEmModoAutomatico();
    }//GEN-LAST:event_rbAutomaticoActionPerformed

    private void rbManualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbManualActionPerformed
        // TODO add your handling code here:
        controller.colocaEmModoManual();
    }//GEN-LAST:event_rbManualActionPerformed

    private void sprAjusteMacroStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_sprAjusteMacroStateChanged
        // TODO add your handling code here:
        Controlador controladorEmExecucao = (Controlador) cmbControladores.getSelectedItem();
        Map<String, Object> valoresSaida = new HashMap<String, Object>();

        for (VariavelControlador v : controladorEmExecucao.getVariaveisTipo(TipoVariavelOPC.MANIPULADA)) {
            Object valorSaida = sprAjusteMacro.getValue();

            valoresSaida.put(v.getNome(), valorSaida);
        }

        controller.setValoresSaida(valoresSaida);
    }//GEN-LAST:event_sprAjusteMacroStateChanged


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bgManuseio;
    private javax.swing.JButton btnExecutar;
    private javax.swing.JButton btnParar;
    private javax.swing.JComboBox cmbControladores;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblEntrada;
    private javax.swing.JLabel lblEntrada1;
    private javax.swing.JLabel lblEntrada2;
    private javax.swing.JLabel lblSaida;
    private javax.swing.JPanel pnlManuseio;
    private javax.swing.JRadioButton rbAutomatico;
    private javax.swing.JRadioButton rbManual;
    private javax.swing.JSpinner sprAjusteMacro;
    // End of variables declaration//GEN-END:variables

    private void listarControladores() {
        ((DefaultComboBoxModel)cmbControladores.getModel()).removeAllElements();

        List<Controlador> controladores = controller.sincronizarControladores(Dados.servidorOPC);

        cmbControladores.addItem("Selecione");

        for (Controlador c : controladores) {
            cmbControladores.addItem(c);
        }
    }

}
